package com.ybzl.common.core.page;

import com.alibaba.fastjson2.JSONObject;
import com.ybzl.common.core.text.Convert;
import com.ybzl.common.utils.ServletUtils;
import org.springframework.util.ObjectUtils;

import java.util.Map;

/**
 * 表格数据处理
 *
 * @author dtf
 */
public class TableSupport {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";

    /**
     * 分页参数合理化
     */
    public static final String REASONABLE = "reasonable";

    /**
     * 封装分页对象
     */
    public static PageDomain getPageDomain() {
        PageDomain pageDomain = new PageDomain();
        //todo 适用 post 的查询方式
        if ("post".equals(ServletUtils.getRequest().getMethod().toLowerCase())) {
            Map<String,Object> rtn = ServletUtils.bodyParams();
            Object pageNum = null;
            Object pageSize = null;
            if (ObjectUtils.isEmpty(rtn) || null == rtn.get("pageNum") || null == rtn.get("pageSize")){
                if(null != rtn.get("params")){
                    pageNum = JSONObject.from(rtn.get("params")).get(PAGE_NUM);
                    pageSize = JSONObject.from(rtn.get("params")).get(PAGE_SIZE);
                }
                pageNum = Convert.toInt(pageNum, 1);
                pageSize = Convert.toInt(pageSize, 10);
            }else{
                pageNum = rtn.get("pageNum");
                pageSize = rtn.get("pageSize");
            }
            pageDomain.setPageNum(Integer.parseInt(String.valueOf(pageNum)));
            pageDomain.setPageSize(Integer.parseInt(String.valueOf(pageSize)));
        }else {
            pageDomain.setPageNum(Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1));
            pageDomain.setPageSize(Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10));
        }
        pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
        pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));
        return pageDomain;
    }
    public static PageDomain buildPageRequest() {
        return getPageDomain();
    }
}
